const { default: traverse } = require('@babel/traverse')
const { default: generator } = require('@babel/generator')
const parser = require('@babel/parser')
const fs = require('fs')
const path = require('path')

const root = path.join(__dirname, '..')

let component_dir = path.join(root, 'src/components')

const lsDirFile = (cwd) => {
  let res = []
  let children = fs.readdirSync(cwd)

  children.forEach((child) => {
    let child_file = path.join(cwd, child)
    if (fs.statSync(child_file).isDirectory()) {
      let c_res = lsDirFile(path.join(cwd, child))
      res.push(...c_res)
    } else if (fs.statSync(child_file).isFile()) {
      res.push(child_file)
    }
  })

  return res
}

let tsxFile = lsDirFile(component_dir).filter((f) => path.extname(f) === '.tsx')

tsxFile.forEach((tsx) => {
  let ast = parser.parse(fs.readFileSync(tsx, 'utf-8'), {
    sourceType: 'module',
    plugins: ['jsx', 'typescript']
  })

  traverse(ast, {
    Program: (pro) => {
      let bodys = pro.node.body
      let bl = bodys.length
      while (bl--) {
        let body = bodys[bl]
        if (
          body.type === 'ImportDeclaration' &&
          body.source.type === 'StringLiteral' &&
          body.source.value === './index.less' &&
          !body.leadingComments?.find((item) => item.value.includes('ignore-remove')) // ignore-remove 注释防删除
        ) {
          // console.log('body====================', body)
          bodys.splice(bl, 1)
        }
      }
    }
  })

  const { code: output } = generator(
    ast,
    {
      /* options */
    },
    tsx
  )
  fs.writeFileSync(tsx, output, 'utf-8')
})
// console.log(files)
